const db = require("../models");
const logger = require("../utils/utils.logger");
const DAO = require("../dao/DAO");
const Shop = db.shop;
const Op = db.Op;

// Create and Save a new Shop
exports.create = async (req, res) => {
  const pm = req.body;
  // 请求验证
  if (!pm.shopName)
    return res.sendResult({
      data: "",
      code: 605,
      message: "店铺名称不能为空！",
    });
  // Create a Shop
  const sort = {
    shopName: pm.shopName,
    // sort_desc: pm.sort_desc,
    // sort_path: pm.sort_path,
  };

  await Shop.findOne({
    where: {
      shopName: pm.shopName
    }
  }).then((singleShop) => {
    if (singleShop && singleShop.id)
      return res.sendResultAto(null, 605, "店铺已存在！");
  });
  // await Shop.findOne({
  //   where: {
  //     shopName: pm.shopName
  //   }
  // }).then((singleShop) => {
  //   if (singleShop && singleShop.id)
  //     return res.sendResultAto(null, 605, "店铺已存在！");
  // });
  DAO.create(Shop, sort, (data) => {
    // logger.debug(`${req.method} ${req.baseUrl + req.path} *** 参数：${JSON.stringify(pm)}; 响应：${JSON.stringify(data)}`);
    res.sendResult(data);
  });
};

// Retrieve all Shop from the database.
exports.findAll = (req, res) => {
  const pm = req.body;

  // pm.raw = false //是否开启原生查询   true 结果：tag.tag_name  false 结果：'tag':{"tag_name": "标签",}

  pm.params.shopName ?
    (pm.params.shopName = {
      [Op.substring]: `%${pm.params.shopName}%`,
    }) :
    (pm.params.shopName = "");

  DAO.list(Shop, pm, (list) => {
    res.sendResult(list);
  });
};

// Find a single Shop with an id
exports.findOne = (req, res) => {
  const pm = req.body;
  DAO.findOne(Shop, pm, (data) => {
    res.sendResult(data);
  });
};

// Update a Shop by the id in the request
exports.update = (req, res) => {
  const pm = req.body;
  // 请求验证
  if (!pm.id)
    return res.sendResult({
      data: "",
      code: 605,
      message: "ID不能为空！"
    });
  DAO.update(Shop, pm, {
    id: pm.id
  }, (data) => {
    res.sendResult(data);
  });
};

// Delete a Shop with the specified id in the request
exports.delete = (req, res) => {
  const pm = req.body;
  // 请求验证
  if (!pm.id)
    return res.sendResult({
      data: "",
      code: 605,
      message: "ID不能为空！"
    });
  DAO.delete(Shop, {
    id: pm.id
  }, (data) => {
    res.sendResult(data);
  });
};

// Delete all Shop from the database.
exports.deleteAll = (req, res) => {
  const pm = req.body;
  DAO.deleteAll(Shop, (data) => {
    res.sendResult(data);
  });
};

// Delete Shop from the database.
exports.query = (req, res) => {
  const pm = req.body;
  let sql = "SELECT * FROM `mg_shopname`";
  DAO.doQuery(sql, (data) => {
    res.sendResult(data);
  });
};